<template>
  <div class="stock-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">库存管理</h1>
      <div class="header-actions">
        <button @click="showInboundModal = true" class="btn-primary">入库</button>
        <button @click="showOutboundModal = true" class="btn-secondary">出库</button>
        <button @click="showInventoryModal = true" class="btn-warning">盘点</button>
        <button @click="exportStock" class="btn-export">导出</button>
      </div>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <div class="filter-row">
        <div class="filter-item">
          <label>商品搜索:</label>
          <input 
            v-model="filters.search" 
            @input="filterStock"
            placeholder="商品名称或编码"
            class="filter-input"
          />
        </div>
        
        <div class="filter-item">
          <label>商品类别:</label>
          <select v-model="filters.category" @change="filterStock">
            <option value="">全部类别</option>
            <option value="食品">食品</option>
            <option value="饮料">饮料</option>
            <option value="日用品">日用品</option>
            <option value="服装">服装</option>
            <option value="电子产品">电子产品</option>
          </select>
        </div>
        
        <div class="filter-item">
          <label>库存状态:</label>
          <select v-model="filters.status" @change="filterStock">
            <option value="">全部状态</option>
            <option value="正常">正常</option>
            <option value="预警">预警</option>
            <option value="缺货">缺货</option>
          </select>
        </div>
        
        <div class="filter-item">
          <label>仓库位置:</label>
          <select v-model="filters.warehouse" @change="filterStock">
            <option value="">全部仓库</option>
            <option value="主仓库">主仓库</option>
            <option value="分仓库A">分仓库A</option>
            <option value="分仓库B">分仓库B</option>
          </select>
        </div>
      </div>
    </div>

    <!-- 库存统计卡片 -->
    <div class="stats-section">
      <div class="stat-card">
        <div class="stat-title">总商品数</div>
        <div class="stat-value">{{ stockStats.totalProducts }}</div>
        <div class="stat-desc">种商品</div>
      </div>
      <div class="stat-card">
        <div class="stat-title">总库存量</div>
        <div class="stat-value">{{ stockStats.totalQuantity }}</div>
        <div class="stat-desc">件</div>
      </div>
      <div class="stat-card warning">
        <div class="stat-title">预警商品</div>
        <div class="stat-value">{{ stockStats.warningProducts }}</div>
        <div class="stat-desc">种</div>
      </div>
      <div class="stat-card danger">
        <div class="stat-title">缺货商品</div>
        <div class="stat-value">{{ stockStats.outOfStock }}</div>
        <div class="stat-desc">种</div>
      </div>
      <div class="stat-card">
        <div class="stat-title">库存总价值</div>
        <div class="stat-value">¥{{ stockStats.totalValue.toFixed(2) }}</div>
        <div class="stat-desc">元</div>
      </div>
    </div>

    <!-- 库存列表表格 -->
    <div class="table-section">
      <div class="table-header">
        <div class="table-title">库存明细</div>
        <div class="table-info">
          共 {{ filteredStock.length }} 条记录
        </div>
      </div>
      
      <div class="table-wrapper">
        <table class="stock-table">
          <thead>
            <tr>
              <th>商品编码</th>
              <th>商品名称</th>
              <th>类别</th>
              <th>规格</th>
              <th>单位</th>
              <th>当前库存</th>
              <th>最低库存</th>
              <th>最高库存</th>
              <th>成本价</th>
              <th>售价</th>
              <th>库存价值</th>
              <th>仓库位置</th>
              <th>状态</th>
              <th>最后更新</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in paginatedStock" :key="item.id" :class="getRowClass(item)">
              <td>{{ item.code }}</td>
              <td>{{ item.name }}</td>
              <td>{{ item.category }}</td>
              <td>{{ item.specification }}</td>
              <td>{{ item.unit }}</td>
              <td class="quantity">{{ item.quantity }}</td>
              <td>{{ item.minStock }}</td>
              <td>{{ item.maxStock }}</td>
              <td class="price">¥{{ item.costPrice.toFixed(2) }}</td>
              <td class="price">¥{{ item.salePrice.toFixed(2) }}</td>
              <td class="price">¥{{ (item.quantity * item.costPrice).toFixed(2) }}</td>
              <td>{{ item.warehouse }}</td>
              <td>
                <span :class="['status-badge', getStatusClass(item)]">
                  {{ getStockStatus(item) }}
                </span>
              </td>
              <td>{{ formatDate(item.lastUpdated) }}</td>
              <td class="actions">
                <button @click="editStock(item)" class="btn-edit">编辑</button>
                <button @click="viewHistory(item)" class="btn-view">历史</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- 分页器 -->
      <div class="pagination" v-if="totalPages > 1">
        <button 
          @click="changePage(currentPage - 1)" 
          :disabled="currentPage <= 1"
          class="page-btn"
        >
          上一页
        </button>
        
        <span class="page-info">
          第 {{ currentPage }} 页 / 共 {{ totalPages }} 页
        </span>
        
        <button 
          @click="changePage(currentPage + 1)" 
          :disabled="currentPage >= totalPages"
          class="page-btn"
        >
          下一页
        </button>
      </div>
    </div>

    <!-- 入库模态框 -->
    <div v-if="showInboundModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>商品入库</h3>
          <button @click="showInboundModal = false" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <div class="form-row">
            <div class="form-item">
              <label>商品选择:</label>
              <select v-model="inboundForm.productId" required>
                <option value="">请选择商品</option>
                <option v-for="item in stockList" :key="item.id" :value="item.id">
                  {{ item.name }} ({{ item.code }})
                </option>
              </select>
            </div>
            <div class="form-item">
              <label>入库数量:</label>
              <input v-model.number="inboundForm.quantity" type="number" min="1" required />
            </div>
          </div>
          <div class="form-row">
            <div class="form-item">
              <label>入库价格:</label>
              <input v-model.number="inboundForm.price" type="number" step="0.01" min="0" required />
            </div>
            <div class="form-item">
              <label>供应商:</label>
              <input v-model="inboundForm.supplier" type="text" />
            </div>
          </div>
          <div class="form-row">
            <div class="form-item full-width">
              <label>备注:</label>
              <textarea v-model="inboundForm.remark" rows="3"></textarea>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="showInboundModal = false" class="btn-cancel">取消</button>
          <button @click="submitInbound" class="btn-primary">确认入库</button>
        </div>
      </div>
    </div>

    <!-- 出库模态框 -->
    <div v-if="showOutboundModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>商品出库</h3>
          <button @click="showOutboundModal = false" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <div class="form-row">
            <div class="form-item">
              <label>商品选择:</label>
              <select v-model="outboundForm.productId" required>
                <option value="">请选择商品</option>
                <option v-for="item in stockList.filter(s => s.quantity > 0)" :key="item.id" :value="item.id">
                  {{ item.name }} ({{ item.code }}) - 库存: {{ item.quantity }}
                </option>
              </select>
            </div>
            <div class="form-item">
              <label>出库数量:</label>
              <input v-model.number="outboundForm.quantity" type="number" min="1" required />
            </div>
          </div>
          <div class="form-row">
            <div class="form-item">
              <label>出库原因:</label>
              <select v-model="outboundForm.reason" required>
                <option value="">请选择原因</option>
                <option value="销售">销售</option>
                <option value="损耗">损耗</option>
                <option value="退货">退货</option>
                <option value="调拨">调拨</option>
                <option value="其他">其他</option>
              </select>
            </div>
            <div class="form-item">
              <label>经手人:</label>
              <input v-model="outboundForm.operator" type="text" required />
            </div>
          </div>
          <div class="form-row">
            <div class="form-item full-width">
              <label>备注:</label>
              <textarea v-model="outboundForm.remark" rows="3"></textarea>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="showOutboundModal = false" class="btn-cancel">取消</button>
          <button @click="submitOutbound" class="btn-primary">确认出库</button>
        </div>
      </div>
    </div>

    <!-- 盘点模态框 -->
    <div v-if="showInventoryModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>库存盘点</h3>
          <button @click="showInventoryModal = false" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <div class="form-row">
            <div class="form-item">
              <label>商品选择:</label>
              <select v-model="inventoryForm.productId" required>
                <option value="">请选择商品</option>
                <option v-for="item in stockList" :key="item.id" :value="item.id">
                  {{ item.name }} ({{ item.code }}) - 当前库存: {{ item.quantity }}
                </option>
              </select>
            </div>
            <div class="form-item">
              <label>实际数量:</label>
              <input v-model.number="inventoryForm.actualQuantity" type="number" min="0" required />
            </div>
          </div>
          <div class="form-row">
            <div class="form-item">
              <label>盘点人:</label>
              <input v-model="inventoryForm.operator" type="text" required />
            </div>
            <div class="form-item">
              <label>盘点日期:</label>
              <input v-model="inventoryForm.date" type="date" required />
            </div>
          </div>
          <div class="form-row">
            <div class="form-item full-width">
              <label>盘点说明:</label>
              <textarea v-model="inventoryForm.remark" rows="3"></textarea>
            </div>
          </div>
          <div v-if="inventoryForm.productId" class="inventory-diff">
            <div class="diff-info">
              <span>当前库存: {{ getCurrentStock(inventoryForm.productId) }}</span>
              <span>实际库存: {{ inventoryForm.actualQuantity || 0 }}</span>
              <span :class="['diff-value', getDiffClass()]">
                差异: {{ getStockDiff() }}
              </span>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="showInventoryModal = false" class="btn-cancel">取消</button>
          <button @click="submitInventory" class="btn-primary">确认盘点</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useStockStore } from '@/stores/stock'

// 使用库存状态管理
const stockStore = useStockStore()

// 响应式数据
const filters = ref({
  search: '',
  category: '',
  status: '',
  warehouse: ''
})

const currentPage = ref(1)
const pageSize = ref(20)

// 模态框显示状态
const showInboundModal = ref(false)
const showOutboundModal = ref(false)
const showInventoryModal = ref(false)

// 表单数据
const inboundForm = ref({
  productId: '',
  quantity: 1,
  price: 0,
  supplier: '',
  remark: ''
})

const outboundForm = ref({
  productId: '',
  quantity: 1,
  reason: '',
  operator: '',
  remark: ''
})

const inventoryForm = ref({
  productId: '',
  actualQuantity: 0,
  operator: '',
  date: new Date().toISOString().split('T')[0],
  remark: ''
})

// 计算属性
const stockList = computed(() => stockStore.stockList)
const filteredStock = computed(() => stockStore.getFilteredStock(filters.value))
const stockStats = computed(() => stockStore.stockStats)

const totalPages = computed(() => {
  return Math.ceil(filteredStock.value.length / pageSize.value)
})

const paginatedStock = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredStock.value.slice(start, end)
})

// 方法
const filterStock = () => {
  currentPage.value = 1
}

const changePage = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
  }
}

const getRowClass = (item) => {
  if (item.quantity <= 0) return 'out-of-stock'
  if (item.quantity <= item.minStock) return 'warning'
  return ''
}

const getStatusClass = (item) => {
  if (item.quantity <= 0) return 'danger'
  if (item.quantity <= item.minStock) return 'warning'
  return 'success'
}

const getStockStatus = (item) => {
  if (item.quantity <= 0) return '缺货'
  if (item.quantity <= item.minStock) return '预警'
  return '正常'
}

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

const closeModal = () => {
  showInboundModal.value = false
  showOutboundModal.value = false
  showInventoryModal.value = false
}

// 入库操作
const submitInbound = () => {
  if (!inboundForm.value.productId || !inboundForm.value.quantity) {
    alert('请填写必要信息')
    return
  }
  
  stockStore.inboundStock({
    ...inboundForm.value,
    date: new Date().toISOString()
  })
  
  // 重置表单
  inboundForm.value = {
    productId: '',
    quantity: 1,
    price: 0,
    supplier: '',
    remark: ''
  }
  
  showInboundModal.value = false
  alert('入库成功')
}

// 出库操作
const submitOutbound = () => {
  if (!outboundForm.value.productId || !outboundForm.value.quantity) {
    alert('请填写必要信息')
    return
  }
  
  const product = stockList.value.find(item => item.id === outboundForm.value.productId)
  if (product.quantity < outboundForm.value.quantity) {
    alert('库存不足')
    return
  }
  
  stockStore.outboundStock({
    ...outboundForm.value,
    date: new Date().toISOString()
  })
  
  // 重置表单
  outboundForm.value = {
    productId: '',
    quantity: 1,
    reason: '',
    operator: '',
    remark: ''
  }
  
  showOutboundModal.value = false
  alert('出库成功')
}

// 盘点操作
const submitInventory = () => {
  if (!inventoryForm.value.productId || inventoryForm.value.actualQuantity === '') {
    alert('请填写必要信息')
    return
  }
  
  stockStore.inventoryStock({
    ...inventoryForm.value,
    date: new Date().toISOString()
  })
  
  // 重置表单
  inventoryForm.value = {
    productId: '',
    actualQuantity: 0,
    operator: '',
    date: new Date().toISOString().split('T')[0],
    remark: ''
  }
  
  showInventoryModal.value = false
  alert('盘点完成')
}

const getCurrentStock = (productId) => {
  const product = stockList.value.find(item => item.id === productId)
  return product ? product.quantity : 0
}

const getStockDiff = () => {
  if (!inventoryForm.value.productId) return 0
  const current = getCurrentStock(inventoryForm.value.productId)
  const actual = inventoryForm.value.actualQuantity || 0
  return actual - current
}

const getDiffClass = () => {
  const diff = getStockDiff()
  if (diff > 0) return 'positive'
  if (diff < 0) return 'negative'
  return 'zero'
}

// 编辑库存
const editStock = (item) => {
  // 这里可以实现编辑功能
  console.log('编辑库存:', item)
}

// 查看历史
const viewHistory = (item) => {
  // 这里可以实现查看历史功能
  console.log('查看历史:', item)
}

// 导出库存
const exportStock = () => {
  stockStore.exportStock(filteredStock.value)
}

// 生命周期
onMounted(() => {
  stockStore.initializeStock()
})
</script>

<style scoped>
.stock-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-title {
  margin: 0;
  color: #333;
  font-size: 24px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.btn-primary, .btn-secondary, .btn-warning, .btn-export {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-primary:hover {
  background: #0056b3;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background: #545b62;
}

.btn-warning {
  background: #ffc107;
  color: #212529;
}

.btn-warning:hover {
  background: #e0a800;
}

.btn-export {
  background: #28a745;
  color: white;
}

.btn-export:hover {
  background: #1e7e34;
}

.filter-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.filter-row {
  display: flex;
  gap: 20px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item label {
  font-weight: 500;
  color: #555;
  white-space: nowrap;
}

.filter-input, .filter-item select {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.stats-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  text-align: center;
  border-left: 4px solid #007bff;
}

.stat-card.warning {
  border-left-color: #ffc107;
}

.stat-card.danger {
  border-left-color: #dc3545;
}

.stat-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.stat-desc {
  font-size: 12px;
  color: #999;
}

.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  overflow: hidden;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.table-title {
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

.table-info {
  color: #666;
  font-size: 14px;
}

.table-wrapper {
  overflow-x: auto;
}

.stock-table {
  width: 100%;
  border-collapse: collapse;
}

.stock-table th,
.stock-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.stock-table th {
  background: #f8f9fa;
  font-weight: 500;
  color: #555;
  white-space: nowrap;
}

.stock-table tr.warning {
  background-color: #fff3cd;
}

.stock-table tr.out-of-stock {
  background-color: #f8d7da;
}

.quantity, .price {
  text-align: right;
  font-family: monospace;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.success {
  background: #d4edda;
  color: #155724;
}

.status-badge.warning {
  background: #fff3cd;
  color: #856404;
}

.status-badge.danger {
  background: #f8d7da;
  color: #721c24;
}

.actions {
  display: flex;
  gap: 8px;
}

.btn-edit, .btn-view {
  padding: 4px 8px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.3s;
}

.btn-edit:hover {
  background: #007bff;
  color: white;
  border-color: #007bff;
}

.btn-view:hover {
  background: #28a745;
  color: white;
  border-color: #28a745;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  padding: 20px;
  border-top: 1px solid #eee;
}

.page-btn {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.page-btn:hover:not(:disabled) {
  background: #007bff;
  color: white;
  border-color: #007bff;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  color: #666;
  font-size: 14px;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.close-btn:hover {
  color: #333;
}

.modal-body {
  padding: 20px;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 16px;
}

.form-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.form-item.full-width {
  flex: 100%;
}

.form-item label {
  font-weight: 500;
  color: #555;
}

.form-item input,
.form-item select,
.form-item textarea {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-item textarea {
  resize: vertical;
  min-height: 80px;
}

.inventory-diff {
  margin-top: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 4px;
}

.diff-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
}

.diff-value.positive {
  color: #28a745;
}

.diff-value.negative {
  color: #dc3545;
}

.diff-value.zero {
  color: #6c757d;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px;
  border-top: 1px solid #eee;
}

.btn-cancel {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  color: #666;
}

.btn-cancel:hover {
  background: #f8f9fa;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .filter-row {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-item {
    flex-direction: column;
    align-items: stretch;
  }
  
  .stats-section {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .form-row {
    flex-direction: column;
  }
  
  .header-actions {
    flex-wrap: wrap;
  }
}

@media (max-width: 480px) {
  .stats-section {
    grid-template-columns: 1fr;
  }
  
  .stock-container {
    padding: 10px;
  }
}
</style>